package com.fengpanlong.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.fengpanlong.entity.Idea;
import com.fengpanlong.util.DBHelp;
import com.fengpanlong.util.Pager;
import com.fengpanlong.util.RowMapper;
import com.fengpanlong.util.StringUtil;

public class IdeaDao {
	private DBHelp<Idea> db = new DBHelp<Idea>();
	
	private class IdeaRowMapper implements RowMapper<Idea> {

		public Idea mapperRow(ResultSet rs) throws SQLException {
			Idea i = new Idea();
			i.setId(rs.getString("id"));
			i.setTitle(rs.getString("title"));
			i.setContent(rs.getString("content"));
			i.setCreatetime(StringUtil.formateTime(rs.getString("createtime")));
			i.setEmployeeId(rs.getString("employeeId"));
			i.setProjectId(rs.getString("projectId"));
			return i;
		}
		
	}
	/**
	 * 查找项目总数
	 * @return 项目总数
	 */
	private int getIdeaCount() {
		String sql = "select count(*) from t_idea";
		return db.executeQueryForCount(sql);
	}
	/**
	 * 想法分页
	 * @param num
	 * @param projectId
	 * @return
	 */
	public Pager<Idea> findPagerOfProjectsByProjectId(int num,
			String projectId) {
		int totalCount = getIdeaCount();
		if(totalCount == 0) {
			return null;
		}
		Pager<Idea> pager = new Pager<Idea>(getIdeaCount(),num);
		String sql = "select id,title,content,createtime,employeeid,projectid from t_idea where projectid = ? order by createtime desc limit ?,? ";
		List<Idea> result = db.executeQueryForList(sql, new IdeaRowMapper(),projectId,pager.getStartIndex(),pager.getPageSize());
		pager.setResult(result);
		return pager;
	}
	/**
	 * 保存想法
	 * @param idea
	 */
	public void save(Idea i) {
		String sql = "insert into t_idea(id,title,content,createtime,employeeid,projectid) values(?,?,?,?,?,?)";
		db.executeSQL(sql, i.getId(),i.getTitle(),i.getContent(),i.getCreatetime(),i.getEmployeeId(),i.getProjectId());
	}
	/**
	 * 通过id查找想法
	 * @param ideaId
	 * @return
	 */
	public Idea findById(String ideaId) {
		String sql = "select id,title,content,createtime,employeeid,projectid from t_idea where id = ?";
		return db.executeQueryForObject(sql, new IdeaRowMapper(), ideaId);
	}
	/**
	 * 通过id删除想法
	 * @param ideaId
	 */
	public void delById(String ideaId) {
		String sql = "delete from t_idea where id = ?";
		db.executeSQL(sql, ideaId);
	}
	/**
	 * 通过评论id查找想法
	 * @param ideaCommentId
	 * @return
	 */
	public Idea findByIdeaCommentId(String ideaCommentId) {
		String sql = "select id,title,content,createtime,employeeid,projectid from t_idea where id in (select ideaid from t_ideacomment where id = ?)";
		return db.executeQueryForObject(sql, new IdeaRowMapper(), ideaCommentId);
	}
	 /**
	  * 更新想法
	  * @param idea
	  */
	public void update(Idea idea) {
		String sql = "update t_idea set title=?,content=? where id = ?";
		db.executeSQL(sql, idea.getTitle(),idea.getContent(),idea.getId());
	}
}
